import React, { Component } from 'react';
import {
  StyleSheet, Text, View, TouchableOpacity,
  PixelRatio, Image, FlatList, ScrollView
} from "react-native";
import { NavigationEvents } from 'react-navigation';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';
import { ProgressModal } from '../../../components/common/ProgressModal';
import { CommonDialog } from '../../../components/common/Dialog';
import OrderDetailsService from '../../../containers/order-new/details/_common/service';
import ModalPicDelComponent from '../../../component/ModalPicDelComponent';
import HTTP from '../../../utils/http'
import { API, API_GENERATE } from '../../../config/api';
import Echarts from 'native-echarts';
import moment from 'moment';
import { CURRENCY } from '../../../utils/helper';
import ToastUtil from '../../../utils/toast';
import { StateSectionNew } from '../../order/approve/details/_component/StateSectionNew';
const arrowIcon = require('../../../imgs/sanjiao3.png');

const scale = GLOBAL.SCALE;

const modalPicDelCfg = {
  visible: false,
  uri: null,
  delTextHide: true,
  delPress: () => { },
  picPress: () => { }
}
const TAB = [
  {
    name: '协议附件',
    id: 0,
  }, {
    name: '订单信息',
    id: 1,
  }
]
export class secondPriceDetail extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      header: null
    }
  };
  constructor(props) {
    super(props);
    this.params = this.props.navigation.state.params;
    console.log(this.params, '99')
    let { taskId, confirmId, processInstanceId, corpId } = this.params || {};
    this.state = {
      tabIndex: 0,
      modalVisibles: false,
      refreshIcon: false,
      status: 'data',
      resData: {
        currentTask: [],
        priceConfirmHeadVO: {
          dqAttachmentId: '',
          sqAttachmentId: ''
        },
        priceConfirmLineVOs: []
      },
      options: [],
      previewModalVisible: false,
      lightBoxData: {
        modalVisible: false,
        onClosePress: this._closeLightBox,
        title: '',
        rowDataList: [],
        status: 'data',
        refreshIcon: false,
      },
      fold: []
    }
    this.confirmId = confirmId
    this.corpId = corpId
    this.taskId = taskId
    this.processInstanceId = processInstanceId
    this.pageNo = 1;
    this.totalPage = 1;
    this.reload = true;
    modalPicDelCfg.picPress = () => {
      modalPicDelCfg.visible = false;
      modalPicDelCfg.uri = null;
      this.setState({
        previewModalVisible: false,
      });
    }
  }
  async componentWillMount() {
    await this._initPage();
  }

  // 初始化数据
  _initPage = async () => {
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload,
    })
    let res = await HTTP.POST(API_GENERATE(API.SECOND_PRICE_DETAIL), { confirmId: this.confirmId })
    if (res) {
      let fold = []
      for (let i = 0; i < res.priceConfirmLineVOs.length; i++) {
        fold.push(false)
      }
      fold[0] = true
      console.log(fold)
      this.setState({
        status: res ? 'data' : 'empty',
        resData: res,
        refreshIcon: false,
        fold
      })
    } else {
      this.setState({
        refreshIcon: false,
        status: 'error'
      })
    }
  }


  //切换
  _tabFn = (tabIndex) => {
    // this.reload = true;
    this.setState({
      tabIndex,
    })
  }
  // 刷新页面
  _onErrorRefresh = () => {
    this.reload = true;
    this._initPage();
  }

  // 审批
  approve = async () => {
    this.setState({ showRejectModal: false, });
    // this.requesting = true;
    let requestParams = {
      confirmId: this.confirmId,
      taskId: this.taskId,
      auditResult: this.auditResult,
      auditRemark: this.remark,
    };
    let text = this.auditResult ? '同意' : '驳回';
    this.setState({ status: 'loading' });
    let res = await HTTP.POST(API_GENERATE(API.SECOND_PRICE_AUDIT), requestParams);
    // this.requesting = false;
    if (res) {
      ToastUtil.showSuccess(`${text}成功`).then(() => {
        this.props.navigation.state.params.callback();
        this.props.navigation.goBack()
      })
    } else {
      this.setState({
        status: 'data'
      })
    }
  }
  // 审批流
  _getCheckApprove = async () => {
    this.setState({ status: 'loading' })
    //查询审批节点
    let responseData1
    responseData1 = await HTTP.GET(API_GENERATE(API.FIND_NODE), {
      bizId: this.confirmId,
      bizObjType: 'PRICE_CONFIRM',
      processInstanceId: this.processInstanceId,
      corpId: this.corpId,
    });
    // console.log(responseData1, '99888888')
    responseData1 = responseData1 && responseData1.map((item) => {
      if (item.auditResult == 9) {
        item.auditResultName = '操作';
      }
      return item;
    })
    let { lightBoxData } = this.state;
    lightBoxData.modalVisible = true;
    lightBoxData.title = '审批状态';
    lightBoxData.rowDataList = responseData1;
    this.setState({
      lightBoxData,
      status: 'data'
    })
  }

  _closeLightBox = () => {
    let { lightBoxData } = this.state;
    lightBoxData.modalVisible = false;
    this.setState({ lightBoxData });
  }

  _renderApprove = (item) => {
    return (
      <View style={styles.flexWhole}>
        {/* <View style={styles.flexWholeName}>
            <Text style={styles.flexWholeTitle} onPress={() => { this._getCheckApprove() }}>审批流</Text>
          </View> */}
        <View style={styles.itemDayTime}>
          <Text style={[styles.consent,]} onPress={() => {
            this.auditResult = 1;
            this.remark = '';
            this.setState({
              showRejectModal: true,
            })
            // this.consentCreate(item)
          }}>同意</Text>
          <Text style={styles.itemdown} onPress={() => {
            this.auditResult = 0;
            this.remark = '';
            this.setState({
              showRejectModal: true,
            })
          }}>驳回</Text>
        </View>
      </View>
    )
  }

  _showFile = async (fileData) => {
    let { fileId, fileExtName, fileName } = fileData || {};
    if (fileExtName == 'pdf') {
      this.props.navigation.navigate('ContractPdfPage', { finalFileId: fileId, title: fileName })
    } else {
      let headObj = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId: fileId }, {
        rejectError: false, //是否将错误数据以reject的方式返回
        handerError: true //统一出错处理 通过toast提示
      }, 30000);
      if (headObj && headObj.image) {
        modalPicDelCfg.visible = true;
        modalPicDelCfg.uri = headObj.image;
        this.setState({ ls: true });
      } else {
        ToastUtil.showWarning("附件异常");
      }
    }

  }

  listOne = () => {
    let { resData } = this.state;
    let { priceConfirmHeadVO, dqAttachmentFile, sqAttachmentFile } = resData
    if (priceConfirmHeadVO.dqAttachmentId) {
      dqAttachmentId = priceConfirmHeadVO.dqAttachmentId.split(',')
    }
    if (priceConfirmHeadVO.sqAttachmentId) {
      sqAttachmentId = priceConfirmHeadVO.sqAttachmentId.split(',')
    }
    return (
      <View style={{ paddingHorizontal: 20 * scale }}>
        {dqAttachmentFile && dqAttachmentFile.length > 0 ?
          <View style={styles.dataBottomItem}>
            <Text style={styles.dataBottomTitle}>单签认价协议附件</Text>
            <View style={styles.fileItem}>
              {dqAttachmentFile.map((item, index) => {
                return (
                  <TouchableOpacity key={index} onPress={() => { this._showFile(item); }}>
                    <Text style={styles.fileText}>
                      【附件{index + 1}】
                      </Text>
                  </TouchableOpacity>
                )
              })}
            </View>
          </View>
          : null
        }
        {sqAttachmentFile && sqAttachmentFile.length > 0 ?
          <View style={styles.dataBottomItem}>
            <Text style={styles.dataBottomTitle}>双签认价协议附件</Text>
            <View style={styles.fileItem}>
              {sqAttachmentFile.map((item, index) => {
                return (
                  <TouchableOpacity key={index} onPress={() => { this.props.navigation.navigate('ContractPdfPage', { finalFileId: item, title: `附件${index + 1}` }) }}>
                    <Text style={styles.fileText}>
                      【附件{index + 1}】
											</Text>
                  </TouchableOpacity>
                )
              })}
            </View>
          </View> : null
        }
      </View>
    )
  }
  listTwo = () => {
    let { fold, resData } = this.state
    let { priceConfirmHeadVO, priceConfirmLineVOs } = resData
    let { confirmType, companyName, corpId } = priceConfirmHeadVO
    return (
      <View style={{ paddingHorizontal: 20 * scale }}>
        <View style={{ marginBottom: 26 * scale }}>
          <Text>认价类型</Text>
          <Text style={{ lineHeight: 20 * scale }}>{confirmType == '1' ? '商品认价（收发货明细全部自动按照商品结算价格执行）' : '收发货明细认价（针对收发货单确认结算价格）'}</Text>
        </View>
        <View>
          {priceConfirmLineVOs.map((item, index) => {
            return (
              <View key={index}>
                <Text style={{ marginBottom: 10 * scale }}>{companyName}</Text>
                <View style={styles.itemBox}>
                  <View style={styles.flexRow}>
                    <TouchableOpacity
                      style={{ flexDirection: 'row', alignItems: 'center' }}
                      onPress={() => {
                        if (confirmType == '1') {
                          this.props.navigation.navigate('OrderDetailsPage', { orderId: item.orderId, choice: { corpId: corpId } })
                        }
                        else {
                          this.props.navigation.navigate('reanddeDetail', { data: item })
                        }
                      }}>
                      <Text style={styles.dataTypeTitle}>{confirmType == '1' ? ('订单号' + item.orderId) : ('收发货单：' + item.sourceCode)}</Text>
                      {
                        item.lineStatus != "1" ? <Text style={styles.abandoned}>{item.lineStatusName}</Text> : null
                      }
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.foldArrow} onPress={() => {
                      let foldnew = fold
                      foldnew[index] = !foldnew[index]
                      this.setState({
                        fold: foldnew
                      })
                      console.log(foldnew)
                    }}>
                      <Image style={fold[index] ? styles.foldArrowImg : null} source={require('../../../imgs/arrow.png')} />
                    </TouchableOpacity>
                  </View>
                  <Text style={styles.dataType}>{item.goodsName}</Text>
                  <View style={styles.dataShopContent}>
                    <View style={styles.dataShopHorizontal}>
                      <Text style={styles.dataShopTitle}>产品组</Text>
                      <Text style={styles.dataShopText}>{item.bizTeamName || '-'}</Text>
                    </View>
                    <View style={styles.dataShopHorizontal}>
                      <Text style={styles.dataShopTitle}>价格（元/吨）</Text>
                      <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                        <Text style={styles.dataShopText}>{item.tempPrice || '-'}</Text>
                        <Text style={styles.zdprice}>暂定价</Text>
                      </View>
                    </View>
                    <View style={styles.dataShopHorizontal}>
                      <Text style={styles.dataShopTitle}>结算单价（元/吨）</Text>
                      <Text style={[styles.dataShopText, item.settlePrice ? { color: 'red' } : null]}>{item.settlePrice || '-'}</Text>
                    </View>
                  </View>
                  {fold[index] ?
                    <View>
                      <View style={styles.dataShopContent}>
                        <View style={styles.dataShopHorizontal}>
                          <Text style={styles.dataShopTitle}>升贴水（元/吨）</Text>
                          <Text style={styles.dataShopText}>{item.udPrice || '-'}</Text>
                        </View>
                        <View style={styles.dataShopHorizontal}>
                          <Text style={styles.dataShopTitle}>公式价（元/吨）</Text>
                          <Text style={[styles.dataShopText, item.formulaPrice ? { color: 'red' } : null]}>{item.formulaPrice || '-'}</Text>
                        </View>
                        {confirmType == '1' ?
                          <View style={styles.dataShopHorizontal}></View> :
                          <View style={styles.dataShopHorizontal}>
                            <Text style={styles.dataShopTitle}>收发货量（吨）</Text>
                            <Text style={styles.dataShopText}>{item.quantity || '-'}</Text>
                          </View>
                        }
                      </View>
                      {confirmType == '2' ?
                        <View style={styles.dataShopContent}>
                          <View style={styles.dataShopHorizontal}>
                            <Text style={styles.dataShopTitle}>结算量（吨）</Text>
                            <Text style={styles.dataShopText}>{item.settlementQuantity || '-'}</Text>
                          </View>
                          <View style={styles.dataShopHorizontal}>
                            <Text style={styles.dataShopTitle}>收发货日期</Text>
                            <Text style={styles.dataShopText}>{item.stockDate ? item.stockDate.substring(0, 11) : '-'}</Text>
                          </View>
                          <View style={styles.dataShopHorizontal}>
                            <Text style={styles.dataShopTitle}>仓库</Text>
                            <Text style={styles.dataShopText}>{item.warehouseName || '-'}</Text>
                          </View>
                        </View>
                        : null}
                      <View style={styles.line}></View>
                      <View style={styles.lineHorazontal}>
                        <Text style={styles.dataLineTitle}>结算公式：</Text>
                        <Text style={styles.dataLineText}>{item.priceFormlaName || '-'}</Text>
                      </View>
                      {confirmType == '2' ?
                        <View style={styles.lineHorazontal}>
                          <Text style={styles.dataLineTitle}>收货方地址：</Text>
                          <Text style={styles.dataLineText}>{item.destAddressName || '-'}</Text>
                        </View> : null}
                      {confirmType == '2' ?
                        <View style={styles.lineHorazontal}>
                          <Text style={styles.dataLineTitle}>发货方地址：</Text>
                          <Text style={styles.dataLineText}>{item.srcAddressName || '-'}</Text>
                        </View> : null}
                      <View style={styles.lineHorazontal}>
                        <Text style={styles.dataLineTitle}>等级优惠价：</Text>
                        <Text style={styles.dataLineText}>{item.rebatePrice || '-'}</Text>
                      </View>
                    </View>
                    : null}

                </View>
              </View>
            )
          })}
        </View>
      </View>
    )

  }

  render() {
    let { tabIndex, status, showRejectModal, lightBoxData } = this.state
    let { currentTask, priceConfirmHeadVO, priceConfirmLineVOs } = this.state.resData
    return (
      <View style={styles.container}>
        <View style={styles.headBox}>
          <View style={styles.topBox}>
            <Common type="headLeft" onPress={() => { this.props.navigation.goBack() }} color='#fff' />
            <Text style={styles.topTitle}>二次认价审批详情</Text>
            <TouchableOpacity style={styles.flexWholeName} onPress={() => { this._getCheckApprove() }}>
              <Text style={styles.flexWholeTitle}>审批流</Text>
            </TouchableOpacity>
          </View>
        </View>
        <View style={styles.flexBox}>
          <Text style={styles.flexTitle}>申请ID: {priceConfirmHeadVO.confirmId || '-'}</Text>
        </View>
        <View style={styles.flexApply}>
          <Text style={styles.flexTitle}>提交人（部门）: {priceConfirmHeadVO.auditByName ? priceConfirmHeadVO.auditByName : '-'}
            {priceConfirmHeadVO.organName ? '（' + priceConfirmHeadVO.organName + ')' : null}
          </Text>
        </View>
        <View style={styles.flexBox}>
          <Text style={styles.flexTitle}>提交时间: {priceConfirmHeadVO.auditTime ? priceConfirmHeadVO.auditTime.substring(0, 11) : '-'}</Text>
        </View>
        <View style={styles.flexBox}>
          <Text style={styles.flexTitle}>申请备注: {priceConfirmHeadVO.remark || '-'}</Text>
        </View>
        <View style={[styles.flexBusiness, styles.flexAccount]}>
        </View>
        <View style={styles.headTitleBox}>
          {TAB.map((items, index) => {
            return (
              <TouchableOpacity key={index} onPress={() => { this._tabFn(index) }} style={{ flex: 1 }}>
                <Text style={[styles.tabItems, tabIndex == index ? styles.tabItemActive : null]}>{items.name}
                </Text>
                {tabIndex == index ? (
                  <Text style={{
                    height: 2 * scale, backgroundColor: '#0E7FFD', flexDirection: 'row', paddingLeft: 3 * scale,
                    paddingRight: 3 * scale, marginHorizontal: 40 * scale
                  }}>
                  </Text>
                ) : null
                }
              </TouchableOpacity>
            )
          })
          }
        </View>
        {status == 'data' ?
          <ScrollView style={{ flex: 1 }}>
            {tabIndex === 0 ?
              this.listOne() : null
            }
            {tabIndex === 1 ?
              this.listTwo() : null
            }
          </ScrollView>
          : null
        }
        {
          status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无数据'} onErrorPress={this._onErrorRefresh} />) : null
        }
        {this._renderApprove()}
        {/* 审批流 */}
        <ProgressModal {...lightBoxData} />
        <ModalPicDelComponent {...modalPicDelCfg} />
        <RefuseModal
          titleText={'审批意见'}
          placeholderText={this.auditResult ? '请输入同意原因' : null}
          propsDefaultValue={this.auditResult ? '审批同意' : '审批驳回'}
          visible={showRejectModal}
          btnPress={(text) => {
            this.remark = text;
            this.approve();
          }}
          bgPress={() => {
            this.setState({
              showRejectModal: false,
            });
          }} />
      </View>
    )

  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.white,
    // paddingBottom: 30 * scale
  },
  flexBusiness: {
    flexDirection: 'row',
    paddingTop: 10 * scale,
    backgroundColor: style.color.themeColor,
    paddingLeft: 28 * scale,
  },
  flexBox: {
    flexDirection: 'row',
    paddingTop: 10 * scale,
    justifyContent: 'space-between',
    backgroundColor: style.color.themeColor,
    paddingLeft: 28 * scale,
    paddingRight: 35 * scale,
  },
  flexTitle: {
    fontSize: 12 * scale,
    color: '#ffffff',
    lineHeight: 18 * scale
  },
  flexApply: {
    flexDirection: 'row',
    paddingTop: 10 * scale,
    justifyContent: 'space-between',
    backgroundColor: style.color.themeColor,
    paddingLeft: 28 * scale,
    paddingRight: 60 * scale,
  },
  flexAccount: {
    paddingBottom: 25 * scale,
  },
  headTitleBox: {
    // backgroundColor: style.color.themeColor,
    marginTop: -15 * scale,
    // height: 50 * scale,
    borderTopLeftRadius: 10 * scale,
    borderTopRightRadius: 10 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: '#fff',
    backgroundColor: '#fff',
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-around',
    // paddingLeft: 60 * scale,
    // paddingRight: 60 * scale,
    // height: 600 * scale,
  },
  tabItems: {
    color: '#0E7FFD',
    fontSize: 12 * scale,
    // width: '35%',
    textAlign: 'center',
    marginTop: 20 * scale,
    opacity: .8,
    paddingRight: 5 * scale,
    paddingLeft: 5 * scale,
    paddingBottom: 5 * scale,
  },
  tabItemActive: {
    opacity: 1,
  },
  flexWhole: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 24 * scale,
    backgroundColor: '#F4F7FE'
  },
  flexWholeName: {
    borderWidth: 1,
    borderColor: '#fff',
    borderRadius: 15 * scale,
    paddingHorizontal: 16,
    paddingVertical: 6
  },
  flexWholeTitle: {
    fontSize: 11,
    color: '#fff'
  },
  itemDayTime: {
    justifyContent: 'flex-end',
    flex: 1,
    flexDirection: 'row'
  },
  consent: {
    paddingHorizontal: 20 * scale,
    paddingVertical: 8 * scale,
    fontSize: 12 * scale,
    opacity: 1,
    color: '#ffffff',
    alignItems: 'center',
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    // marginRight: 0 * scale,
    flexDirection: 'row',
    backgroundColor: style.color.themeColor,
    overflow: 'hidden'
  },
  itemdown: {
    fontSize: 12 * scale,
    color: style.color.themeColor,
    alignItems: 'center',
    paddingHorizontal: 20 * scale,
    paddingVertical: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    marginRight: 20 * scale,
    flexDirection: 'row',
    marginLeft: 10 * scale,
  },
  dataBottomTitle: {
    fontSize: 14 * scale,
    color: '#000000',
    marginTop: 27 * scale,
    marginBottom: 10 * scale,
  },
  fileItem: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10 * scale,
    flexWrap: "wrap"
  },
  fileText: {
    fontSize: 12 * scale,
    color: '#0091FF',
    marginBottom: 10 * scale,
  },
  headBox: {
    paddingTop: 50 * scale,
    backgroundColor: style.color.themeColor,
    paddingBottom: 20 * scale,
  },
  topTitle: {
    fontSize: 18 * scale,
    color: '#fff',
    fontWeight: '600'
  },
  topBox: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 18
  },
  itemBox: {
    backgroundColor: "#F4F7FE",
    borderRadius: 5 * scale,
    padding: 10 * scale,
    marginBottom: 25 * scale
  },
  flexRow: {
    flexDirection: 'row',
    alignItems: "center",
    justifyContent: 'space-between'
  },
  dataShopItem: {
    backgroundColor: '#F4F7FE',
    borderRadius: 5 * scale,
    paddingVertical: 9 * scale,
    paddingHorizontal: 18 * scale,
    marginBottom: 14 * scale
  },
  dataTypeTitle: {
    fontSize: 14 * scale,
    color: '#0091FF',
    fontWeight: '600'
  },
  dataType: {
    fontSize: 14 * scale,
    color: '#09090A',
    fontWeight: '600'
  },
  dataShopContent: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 14 * scale
  },
  dataShopHorizontal: {
    flex: 1,
  },
  dataShopTitle: {
    fontSize: 12 * scale,
    color: '#000000',
    marginBottom: 5 * scale,
    opacity: 0.7
  },
  dataShopText: {
    fontSize: 12 * scale,
    color: '#000000',
    fontWeight: '600',
    marginBottom: 5 * scale,
    lineHeight: 20 * scale
  },
  foldArrow: {
    flex: 1,
    alignItems: 'flex-end',
    paddingVertical: 10 * scale,
    paddingRight: 20 * scale
  },
  foldArrowImg: {
    transform: [{ rotate: '90deg' }]
  },
  line: {
    marginTop: 10 * scale,
    marginBottom: 10 * scale,
    height: 1 / PixelRatio.get(),
    backgroundColor: "#979797",
    opacity: 0.4
  },
  lineHorazontal: {
    flexDirection: 'row',
    marginBottom: 10 * scale,
  },
  dataLineTitle: {
    fontSize: 12 * scale,
    width: 75 * scale,
    textAlign: 'right',
    lineHeight: 20 * scale
  },
  dataLineText: {
    fontSize: 12 * scale,
    color: '#000000',
    fontWeight: '600',
    flex: 1,
    lineHeight: 20 * scale
  },
  zdprice: {
    backgroundColor: 'rgba(250,100,0,0.10)',
    borderRadius: 2 * scale,
    color: '#FA6400',
    fontSize: 10,
    paddingVertical: 3 * scale,
    paddingHorizontal: 7 * scale,
    marginLeft: 8 * scale,
    marginBottom: 5 * scale,
  },
  abandoned: {
    marginLeft: 10 * scale,
    fontSize: 12 * scale,
    color: 'red'
  }
})